package com.wenhua.junshao.controller;

import com.wenhua.junshao.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController

@RequestMapping("/common")
public class CommonController {

    /**
     * 文件上传
     */
    @Value("${junshao.path}")
    private String basePath;

    @PostMapping("upload")
    //File从前端获取
    public R<String> upload(MultipartFile file) throws IOException {

        //原始文件名
        String originalFilename = file.getOriginalFilename();
        //文件名后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //加上uuid防止重复
        String fileName = UUID.randomUUID().toString() + suffix;


        //创建一个目录对象
        File dir = new File(basePath);
        //判断当前目录是否存在

        if (!dir.exists()) {
            //不存在,就创建
            dir.mkdirs();
        }
        //将临时文件存放到指定位置
        file.transferTo(new File(basePath + fileName));

        return R.success(fileName);
    }


    /**
     * 文件下载
     */
    @GetMapping("download")
    public void Download(String name, HttpServletResponse response) throws IOException {
        //输入流:获取文件的输入流
        FileInputStream is = new FileInputStream(basePath + name);
        //输出流：response的输出流
        ServletOutputStream os = response.getOutputStream();
        //输入流与输出流的拷贝
        IOUtils.copy(is, os);
    }
}
